package com.hula.onion.book.server.spider.platforms.licaifan;

import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.LoginForm;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.model.AccountInfo;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Description:
 * Create Date:2018/1/30 19:49
 *
 * @author liangbing
 * @version 1.0
 */
@Component
public class LiCaiFanSpiderHelper {

    /**
     * 组装请求参数
     *
     * @param form
     * @return
     */
    public Map<String, Object> installRequestParams(LoginForm form) {

        Map<String, Object> map = new HashMap<>(4);

        map.put("username", form.getUserName());
        map.put("password", form.getPassword());
        map.put("vcode", form.getTicket());
        map.put("rg_agreement", "1");

        return map;

    }

    /**
     * 解析登陆结果
     *
     * @param html
     * @return
     */
    public String parseLoginResult(String html) {

        Document dc = Jsoup.parse(html);

        Element element = dc.selectFirst("div.jump");

        String result = element.getAllElements().get(1).text();

        return result;
    }

    /**
     * 解析账户余额
     *
     * @param html
     * @return
     */
    public CommonResponse parseAccountBalance(String html) {
        if (StringUtils.isEmpty(html)) {
            return new CommonResponse(ResponseStatusEnum.FAIL);
        }
        try {
            AccountInfo accountInfo = new AccountInfo();

            Document dc = Jsoup.parse(html);
            Element element = dc.selectFirst("div.property-count");
            String yesterdayInterest = element.getAllElements().get(8).text();
            String yFinal = StringUtils.removePattern(yesterdayInterest, "['￥',' 元']");
            accountInfo.setYesterdayIntrest(new BigDecimal(yFinal));

            String totalInterest = element.getAllElements().get(17).text();
            String tFinal = StringUtils.removePattern(totalInterest, "['￥',' 元']");
            accountInfo.setTotalIntrest(new BigDecimal(tFinal));

            String amount = element.getAllElements().get(27).text();
            accountInfo.setAmount(new BigDecimal(amount));

            return new CommonResponse(accountInfo);
        } catch (Exception e) {
            return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
        }
    }

}
